import axios from 'axios'
//本地
//export const BASE_URL = 'http://lv.fxoa.com';

//远程
export const BASE_URL = process.env.BASE_URL;

//export const APP_VUE_UPLOAD_URL = BASE_URL + '/oa/uploadFiles'
export const APP_VUE_UPLOAD_URL = process.env.UPLOAD_URL;

const app_key = 'o7gK3H2fCh7hqiKVwGrU7l9LYruy2E/87tVHoNjIPVI=';

var userinfo = {};

//职位状态
const state_list = ['离职','正常','待离职'];


//性别
const sex_list = ['保密','男','女'];

function token()
{
   // 对字符串进行编码
   var encode = encodeURI(app_key);
   // 对编码的字符串转化base64
   var base64 = btoa(encode);
   return base64;
}


/*
  　　 * 参数说明：
  　　 * number：要格式化的数字
  　　 * decimals：保留几位小数
  　　 * dec_point：小数点符号
  　　 * thousands_sep：千分位符号
        //格式化数字
  　　 * */
function fmoney(number) {
  if(number == '' || number == '0' || number == 'NaN' || !number) return "0.00";
   number = number.toString();
   let s = number.replace('/[A-Z]/','').trim()
  let n = 2;
  s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  console.log('s: ' + s)
  var l = s.split(".")[0].split("").reverse(),
    r = s.split(".")[1];
  let t = "";
  for(let i = 0; i < l.length; i ++ )
  {
    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
  }
  return t.split("").reverse().join("") + "." + r;

}


//常用验证规则
var formRule =  {
  account:[
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  username: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
    {
      required: true,
      pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
      message: '姓名不支持特殊字符',
      trigger: 'blur'
    }
  ],
    idcard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { min: 15, max: 18, message: '请如实填写18位号码，以供学校保卫科核对', trigger: 'blur' },
    {
      required: true,
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号码',
      trigger: 'blur'
    }
  ],
  mobile:[
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {type:'number',max:11,min:11,message:'请输入11位手机号', trigger: 'blur' },
    {
      required: true,
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  date: [
    { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
  ],
  email: [
    { type: 'email', required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
  sex:[{type:'number',required: true,message:'请输入性别', trigger: 'blur' },],
};
//判断字符串是否为空
function isNull(str)
{
  if(str == null || str == '' || str == undefined) return true;
  return false;
}

//对比数据差异
function getDiffObj(object, other) {
  let diff = {}
  let vChildren
  for (var key in object) {
    if (typeof object[key] === 'object' && typeof other[key] === 'object' && object[key] && other[key]) {
      vChildren = getDiffObj(object[key], other[key])
      if (Object.keys(vChildren).length > 0) {
        diff[key] = vChildren
      }
    } else if (object[key] !== other[key]) {
      diff[key] = object[key]
    }
  }
  if (JSON.stringify(diff) == '{}') {
    return null
  } else {
    return diff
  }
}

//处理文件
function clearMoney(){
   return '';
}


//还原金额
function resetMoney(str) {
  if (!str) {
    return 0;
  }
  if (typeof (str) == 'number') {
    return str;
  }
  let num = parseFloat(str.replace(/[^\d\.-]/g, ""));
  return num;
}

function getUserInfo(){
  let userInfo = sessionStorage.getItem('userinfo');
  if(isNull(userInfo)) return '';
  return JSON.parse(userInfo);

}

//下载文件

function downloadFile(url,fileName='未知文件') {
  axios({
    method: 'post',
    url: BASE_URL + '/oa/downloadFiles',
    headers: {'Content-type': 'application/json;charset:utf-8;'},
    data: {fileUrl: url,fileName: fileName},
    responseType: 'blob'
  }).then((res) => {
    const blob = new Blob([res.data]);
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a');
      elink.download = fileName;
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);// 释放URL 对象
      document.body.removeChild(elink);
      //this.loading = false;
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName);
      //this.loading = false;
    }
  }).catch((err) => {
    console.log(err);
    //this.loading = false;
  });
}

const tracfficList = [
  {name: '火车',id: 1},
  {name: '飞机',id: 2},
  {name: '其他',id: 3},
];
  const tracfficArea = [
  {id:1,name:'上午'},
  {id:2,name:'中午'},
  {id:3,name:'下午'},
  {id:4,name:'晚上'},
];

function previewOffice(fileUrl) {
  // 文件的下载地址(可直接访问的)
// 将 URL encode 一下；
  let newFileUrl = encodeURIComponent(fileUrl)
// 预览
  window.open('https://view.officeapps.live.com/op/view.aspx?src=' + newFileUrl, '_blank')
}

// 格式化日对象
 const getNowDate = () => {
  var date = new Date();
  var sign2 = ":";
  var year = date.getFullYear() // 年
  var month = date.getMonth() + 1; // 月
  var day = date.getDate(); // 日
  var hour = date.getHours(); // 时
  var minutes = date.getMinutes(); // 分
  var seconds = date.getSeconds() //秒
  var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
  var week = weekArr[date.getDay()];
  // 给一位数的数据前面加 “0”
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
}

const resetFormData = (param) => {
  Object.keys(param).forEach(key => {
        param[key] = '';
  });
  return param;
}


export default{
    BASE_URL,
    token,
    fmoney,
    formRule,
    isNull,
    state_list,
    sex_list,
    APP_VUE_UPLOAD_URL,
    getDiffObj,
    resetMoney,
    getUserInfo,
    downloadFile,
    tracfficList,
    tracfficArea,
   previewOffice,
   getNowDate,
   resetFormData,
   clearMoney
}
